//
//  LoginView.swift
//  SCA
//
//  Created by tjun on 2025/9/2.
//

import UIKit
import TTTAttributedLabel


class LoginView: UIView {

    let usernameTextField = LabeledTextField(tip: "用户名 至少6个字符，必须由字母和数字所组合。".localizedString)
    let passwordTextField = LabeledTextField(tip: "密码 至少8个字符，必须由字母,数字和特殊字符组合。".localizedString)
    let forgetPasswordButton = UIButton(type: .system, title: "忘记密码".localizedString, textColor: Assets.Color.hex00CCFF)
    private let confirmButton = MainButton(type: .system, title: "确认".localizedString, font: UIFontMake(16), textColor: .white)

    var lastView: UIView!
    
    var onAgreementLabeLinkTaped: ((URL) -> Void)?
    var onConfirmButtonTaped: (() -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        
        usernameTextField.titleAttributedText = "用户名*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        usernameTextField.textField.keyboardType = .asciiCapable
        addSubview(usernameTextField)
        usernameTextField.textField.addTarget(self, action: #selector(textFieldDidChange(_ :)), for: .editingChanged)
        usernameTextField.snp.makeConstraints { make in
            make.top.equalTo(24)
            make.left.right.equalToSuperview().inset(AppStyle.margin.left)
        }
        
        passwordTextField.titleAttributedText = "密码*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        addSubview(passwordTextField)
        passwordTextField.textField.keyboardType = .asciiCapable
        passwordTextField.textField.addTarget(self, action: #selector(textFieldDidChange(_ :)), for: .editingChanged)
        passwordTextField.snp.makeConstraints { make in
            make.top.equalTo(usernameTextField.snp.bottom).offset(20)
            make.left.right.equalTo(usernameTextField)
        }
        
        forgetPasswordButton.addTo(self)
        forgetPasswordButton.sizeToFit()
        forgetPasswordButton.snp.makeConstraints { make in
            make.right.equalTo(passwordTextField)
            make.top.equalTo(passwordTextField.snp.bottom).offset(10)
            make.width.equalTo(forgetPasswordButton.size.width)
            make.height.equalTo(forgetPasswordButton.size.height)
        }
        
        let agreementText = "点击‘确认’按钮，视为您已阅读并同意本《服务条款》全部条款".localizedString
        let agreementLabel = TTTAttributedLabel().addTo(self)
        agreementLabel.numberOfLines = 0
        agreementLabel.isUserInteractionEnabled = true
        agreementLabel.snp.makeConstraints { make in
            make.left.right.equalTo(usernameTextField)
            make.centerX.equalToSuperview()
            make.top.equalTo(forgetPasswordButton.snp.bottom).offset(20)
        }
        
        let attributedText = NSMutableAttributedString(string: agreementText)
        let range = (agreementText as NSString).range(of: "《服务条款》".localizedString)
        
        let fullRange = NSRange(location: 0, length: agreementText.count)
        attributedText.addAttribute(.font, value: UIFont.systemFont(ofSize: 14), range: fullRange)
        attributedText.addAttribute(.foregroundColor, value: Assets.Color.loginAgreementTitle, range: fullRange)
        attributedText.addAttribute(.foregroundColor, value: Assets.Color.hex00CCFF, range: range)
        agreementLabel.delegate = self
        agreementLabel.linkAttributes = [
            NSAttributedString.Key.foregroundColor: Assets.Color.hex00CCFF,
        ]

        agreementLabel.activeLinkAttributes = [
            NSAttributedString.Key.foregroundColor: Assets.Color.hex00CCFF.withAlphaComponent(0.5)
        ]
        agreementLabel.setText(attributedText)
        
        if let URL = URL(string: "https://www.baidu.com") {
            let range = (agreementText as NSString).range(of: "《服务条款》".localizedString)
            agreementLabel.addLink(to: URL, with: range)
        }
        
        confirmButton.addTo(self)
        confirmButton.isEnabled = false
        confirmButton.addTarget(self, action: #selector(confirmButtonTapped), for: .touchUpInside)
        confirmButton.snp.makeConstraints { make in
            make.left.right.equalTo(usernameTextField)
            make.height.equalTo(AppStyle.size.buttonHeight.scaled)
            make.top.equalTo(agreementLabel.snp.bottom).offset(16)
        }
        
        if AppEnvironment.isDebug {
            usernameTextField.textField.text = "test22"
            passwordTextField.textField.text = "123456Aa@"
        }
     
        textFieldDidChange(usernameTextField.textField)
   
        lastView = confirmButton
    }
    
    @objc func confirmButtonTapped() {
        onConfirmButtonTaped?()
    }
    
    @objc func textFieldDidChange(_ sender: UITextField) {
        if let username = usernameTextField.textField.text, let password = passwordTextField.textField.text {
            confirmButton.isEnabled = isValidUsername(username) && isValidPassword(password)
        } else {
            confirmButton.isEnabled = false
        }
    }
}


extension LoginView: TTTAttributedLabelDelegate {
    func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL!) {
        onAgreementLabeLinkTaped?(url)
    }
}
